<template>
  <div class="all" >
    <div class="log">
      <div class="login">
        <form>
          <div class="login-top-grid">
            <p><h3>用户注册</h3></p>
            <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef"
                     style="margin: 10px 50px;  width: 300px;  height: 70px;">
              <el-form-item prop="username">
                <el-input v-model="form.username" :maxlength="8" type="text" placeholder="用户名">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="form.password" :maxlength="16" type="password" placeholder="密码">
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password_repeat">
                <el-input v-model="form.password_repeat" :maxlength="16" type="password" placeholder="重复密码">
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="email">
                <el-input v-model="form.email" type="email" placeholder="电子邮件地址">
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code">
                <el-row :gutter="10" style="width: 100%">
                  <el-col :span="17">
                    <el-input v-model="form.code" :maxlength="6" type="text" placeholder="请输入验证码">
                      <template #prefix>
                        <el-icon><EditPen /></el-icon>
                      </template>
                    </el-input>
                  </el-col>
                  <el-col :span="5">
                    <el-button type="success" @click="validateEmail"
                               :disabled="!isEmailValid || coldTime > 0">
                      {{coldTime > 0 ? '请稍后 ' + coldTime + ' 秒' : '获取验证码'}}
                    </el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form>
          </div>
        </form>
      </div>
    </div>
    <div class="reg">
      <div class="reg_1">
        <h2>已有账号？</h2>
        <p>如果您已加入我们，请返回登录</p>
        <el-link style="color: #999999" @click="router.push('/')">
          <button  class="register" @click="router.push('/')">返回登录</button>
        </el-link>
        <div style="margin-top: 70px;">
          <el-button style="width: 270px;height: 38px" type="warning" @click="register" plain>立即注册</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {EditPen, Lock, Message, User} from "@element-plus/icons-vue";
import router from "@/router/index.js";
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import {post, get} from "@/net/index.js";

const form = reactive({
    username: '',
    password: '',
    password_repeat: '',
    email: '',
    code: ''
})

const validateUsername = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else if(!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)){
        callback(new Error('用户名不能包含特殊字符，只能是中文/英文'))
    } else {
        callback()
    }
}

const validatePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== form.password) {
        callback(new Error("两次输入的密码不一致"))
    } else {
        callback()
    }
}

const rules = {
    username: [
        { validator: validateUsername, trigger: ['blur', 'change'] },
        { min: 2, max: 8, message: '用户名的长度必须在2-8个字符之间', trigger: ['blur', 'change'] },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码的长度必须在6-16个字符之间', trigger: ['blur', 'change'] }
    ],
    password_repeat: [
        { validator: validatePassword, trigger: ['blur', 'change'] },
    ],
    email: [
        { required: true, message: '请输入邮件地址', trigger: 'blur' },
        {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
    ],
    code: [
        { required: true, message: '请输入获取的验证码', trigger: 'blur' },
    ]
}

const formRef = ref()
const isEmailValid = ref(false)
const coldTime = ref(0)

const onValidate = (prop, isValid) => {
    if(prop === 'email')
        isEmailValid.value = isValid
}

const register = () => {
    formRef.value.validate((isValid) => {
        if(isValid) {
            post('/api/auth/register', {
                username: form.username,
                password: form.password,
                email: form.email,
                code: form.code
            }, (message) => {
                ElMessage.success(message)
                router.push("/")
            })
        } else {
            ElMessage.warning('请完整填写注册表单内容！')
        }
    })
}

const validateEmail = () => {
  coldTime.value = 60
  get(`/api/auth/valid-register-email?email=${form.email}&type=register`, () => {
    ElMessage.success(`验证码已发送到邮箱: ${form.email}，请注意查收`)
    const handle = setInterval(() => {
      coldTime.value--
      if(coldTime.value === 0) {
        clearInterval(handle)
      }
    }, 1000)
  }, undefined, (message) => {
    ElMessage.warning(message)
    coldTime.value = 0
  })
}
</script>

<style scoped>

html, body {
  height: 100%;
  margin: auto;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

.all {
  width: 800px;
  box-shadow: -10px 10px 25px rgba(210, 210, 210, 0.9);
  display: flex;
  border-radius: 35px;
  background-color: #ffffff;
  height: 550px;
  margin: auto;
}

.log {
  width: 50%;
  margin-top: 70px;
}

.reg {
  width: 50%;
  height: 100%;
  margin: auto;
  background-color: #20b2aa;
  border-radius: 35px;
  color: #ffffff;
}

.reg_1 {
  text-align: center;
  margin: 50% auto auto;
}

.reg_1 h2 {
  font-weight: 700;
}

.reg_1 p {
  margin: 15px 0 25px 0;
}

.register {
  width: 70px;
  height: 30px;
  border-radius: 12px;
  background-color: #20b2aa;
  border-color: #fff;
  color: #ffffff;
}

.reg_1 a {
  color: #ffffff;
}

h3 {
  font-size: 3em;
  color: black;
  padding-bottom: 1em;
  margin: 0;
  text-align: center;
  font-family: "Marvel-Regular", serif;
}

span {
  color: #999;
  font-size: 0.85em;
  padding-bottom: 0.2em;
  display: block;
  text-transform: uppercase;
  margin-bottom: 4px;
}

.login-top-grid {
  color: black;
  padding-bottom: 1em;
  font-family: "Marvel-Regular", serif;
  margin: 10px 0;
}
</style>